package com.example.selfcontrol.filter;

import com.example.selfcontrol.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Array;

@WebFilter(urlPatterns = {"/users/auth/*" , "/comments/sendComment"})
// 用户鉴权拦截器
// 用户评论拦截器

public class UserAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    // 对用户视图进行拦截
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("/users/auth/拦截到请求");

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        if(httpRequest.getMethod().equals("OPTIONS")) {
            // 吃掉OPTIONS请求，因为他上面没有authorization头，会卡出跨域报错
            filterChain.doFilter(servletRequest,servletResponse);
        }

        String authorizationHeader = httpRequest.getHeader("Authorization");
        if(authorizationHeader == null) return;
        String jwtToken = authorizationHeader.substring(7) ; // 去除bearer前缀

        boolean validate = JwtUtils.validateToken(jwtToken) ;
        System.out.println("是否放行:  " + validate);
        if(validate && jwtToken != null) {
            filterChain.doFilter(servletRequest,servletResponse);
//                filterChain.doFilter(servletRequest.setAttribute(),servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
